package com.gds.service.impl;

import com.gds.service.AysnService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;



@Service
public class AysnServiceImpl  implements AysnService {
    /**
     * 分布式过期时间
     */
    public final static Long DINGDING_BOSS_SYNC_lOCK_HOLD_TIME = 5*60L*1000;
    /****
     * 100
     */
    public final static Long DINGDING_BOSS_SYNC_lOCK_WAIT_TIME = 100L;

    @Autowired
    private RedissonClient redissonClient;
    @Async
    @Override
    public void getSy(HttpServletRequest request) {

        String userIpAddr = request.getRemoteAddr();
        String key = "xxxxx";
        RLock lock = redissonClient.getLock(key);
        boolean islock = false;
        try {
            islock =lock.tryLock(DINGDING_BOSS_SYNC_lOCK_WAIT_TIME,DINGDING_BOSS_SYNC_lOCK_HOLD_TIME, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (islock) {
            try {
                System.out.println(userIpAddr+" 获取到钉钉同步数据分布式锁  ok");

                try {
                    Thread.sleep(60000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } finally {
                if(lock.isHeldByCurrentThread()) {
                    lock.unlock();
                    System.out.println(userIpAddr +" 释放钉钉同步数据分布式锁 unlock ok");
                }

            }
        } else {
            System.out.println(userIpAddr+"未获取到钉钉同步数据分布式锁 fail");
        }

    }
}
